package cn.summit.passwordsty.rsa;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Base64;

import org.apache.commons.io.FileUtils;

/**
 * @author summit
 * @since 2021/8/15 14:04
 */
public class KeyGeneratorTool {
	public static void main(String[] args) throws IOException, NoSuchAlgorithmException {
		generateKeyAsFile(null, null, "RSA");
	}

	/**
	 * 生成私钥 公钥 并生成文件到本地
	 */
	public static void generateKeyAsFile(String pubFilePath, String priFilePath, String algorithm) throws NoSuchAlgorithmException, IOException {
		KeyPairGenerator instance = KeyPairGenerator.getInstance(algorithm);
		KeyPair keyPair = instance.generateKeyPair();
		PrivateKey aPrivate = keyPair.getPrivate();
		PrivateKey bPrivate = keyPair.getPrivate();

		PublicKey aPublic = keyPair.getPublic();
		byte[] encoded = aPrivate.getEncoded();
		byte[] encoded1 = aPublic.getEncoded();
		String pri = Base64.getEncoder().encodeToString(encoded);
		System.out.println("generator 私钥：" + pri);
		System.out.println("generator 私钥2：" + Base64.getEncoder().encodeToString(bPrivate.getEncoded()));
		;
		String pub = Base64.getEncoder().encodeToString(encoded1);
		System.out.println("generator 公钥：" + pub);

		if (pubFilePath != null) {
			FileUtils.writeStringToFile(new File(pubFilePath), pub, StandardCharsets.UTF_8.name());
			FileUtils.writeStringToFile(new File(priFilePath), pri, StandardCharsets.UTF_8.name());
		}

	}
}
